package com.ojoin.trade.supplyloan_core.web.messagequeue;

import java.io.File;
import java.io.IOException;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import redis.clients.jedis.JedisPubSub;

import com.ojoin.trade.common.utils.CommonUtils;
import com.ojoin.trade.common.utils.LogUtils;
import com.ojoin.trade.common.utils.file.ObjectSaveFileUtils;
import com.ojoin.trade.supplyloan_core.web.domain.CatchDataResultMessage;
import com.ojoin.trade.supplyloan_core.web.service.impl.CatchDataMessageServiceImpl;
@Scope
@Service
public class SubscriberByObject extends JedisPubSub {

	@Autowired 
	public CatchDataMessageServiceImpl catchDataMessageService;
 
	//private BaseDaoImpl baseDao = SpringUtils.getBean("BaseDaoImpl");
	public static final String CHANNEL = "catchData"; 
	private static Logger log = LoggerFactory
			.getLogger(SubscriberByObject.class);

	// 取得订阅的消息后的处理
	public void onMessage(String channel, String message) {
		LogUtils.info(log, "channel-->" + channel+ "数据已接受");

		try{
			Object ob = CommonUtils.deserialize(message);
			   
			deal(ob);
		}catch(Exception e){
			LogUtils.info(log, "onMessage");
			LogUtils.error(log, e);
		}
		
 
	}

	void saveFile(Object ob) {
		String filePath = System.getProperties().getProperty("user.home")
				+ File.separator + "Downloads" + File.separator + "webdriver";

		File file;
		try {
			file = ObjectSaveFileUtils.getFile(filePath,
					"tianmao.object" + ob.hashCode());
			LogUtils.info(log, "WebDriver保存路径为-->" + file.getAbsolutePath());

			CommonUtils.serializedVo(file, ob);
		} catch (IOException e) {
			
			e.printStackTrace();
		}

	}

	// 初始化订阅时候的处理
	public void onSubscribe(String channel, int subscribedChannels) {
		System.out.println("onSubscribe:" + channel);
	}

	// 取消订阅时候的处理
	public void onUnsubscribe(String channel, int subscribedChannels) {
		System.out.println("onUnsubscribe:" + channel);
	}

	// 初始化按表达式的方式订阅时候的处理
	public void onPSubscribe(String pattern, int subscribedChannels) {
		// System.out.println(pattern + "=" + subscribedChannels);
	}

	// 取消按表达式的方式订阅时候的处理
	public void onPUnsubscribe(String pattern, int subscribedChannels) {
		// System.out.println(pattern + "=" + subscribedChannels);
	}

	// 取得按表达式的方式订阅的消息后的处理
	public void onPMessage(String pattern, String channel, String message) {
		System.out.println(pattern + "=" + channel + "=" + message);
	}

	public void deal(Object ob) {
		if (ob instanceof CatchDataResultMessage) {
			catchDataMessageService.filter((CatchDataResultMessage) ob);
		} else if (ob instanceof List<?>) {
			// TODO
			/*
			 * List list=(List)ob; baseDao.setSqlNamespaceByEntiy(list.get(0));
			 * baseDao.insertBatch((List) ob);
			 */
		} else {
			/*
			 * baseDao.setSqlNamespaceByEntiy(ob); baseDao.insert(ob);
			 */
		}
	}

}
